package com.med.meddataintegrator.jwt.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.med.meddataintegrator.common.basic.response.JsonResult;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 过滤器中响应参数 专属返回
 */


public class ResultUtil {


    public static void ok(HttpServletResponse response, JsonResult result) throws JsonProcessingException {
        //设置响参的格式
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");

        //将jsonResult 转换成json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(result);

        //将json字符串写入到response中
        PrintWriter writer = null;
        try {
           writer =  response.getWriter();
           writer.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }

    }


    public static void error(HttpServletResponse response, JsonResult result) throws JsonProcessingException {
        //设置响参的格式
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(result);
        PrintWriter writer = null;
        try {
            writer =  response.getWriter();
            writer.println(jsonString);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }
    }


    public static void error(HttpServletResponse response, int status, JsonResult result) throws JsonProcessingException {
        //设置响参的格式
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        response.setContentType("application/json");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(result);
        PrintWriter writer = null;
        try {
            writer =  response.getWriter();
            writer.println(jsonString);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }
    }
}
